package com.webdemo9.contrller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.webdemo9.bean.UsersBean;
import com.webdemo9.dao.UsersDao;
import com.webdemo9.dao.impl.MD5Encryption;
import com.webdemo9.dao.impl.UsersDaoFactory;

/**
 * 登录系统
 * @author lovemanai
 *
 */
public class IndexProcess extends HttpServlet {
	
	private UsersDao usersDao = UsersDaoFactory.getUsersDao();
	
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username, password, flag;
		username = request.getParameter("username");
		password = request.getParameter("password");
		flag = request.getParameter("flag");
		UsersBean ub = usersDao.usersLogin(username);
		if(ub != null) {
			if(username.equals(ub.getUsername()) && MD5Encryption.MD5Encode(password).equals(ub.getPwd())) {
				if(flag != null) {
					Cookie cookie = new Cookie("username", username);
					cookie.setMaxAge(3600*24*30);
					response.addCookie(cookie);
				}
				request.getSession().setAttribute("username", username);
				response.sendRedirect("listUsers?username=" + username);
			} else {
				response.sendRedirect("index.jsp?errorcode=1"); //用户名或密码错误
			}
		} else {
			response.sendRedirect("index.jsp?errorcode=2"); //用户不存在
		}
		
	}

}
